<template>
  <el-dialog v-el-drag-dialog :title="!form.id?'新建优惠券':'编辑优惠券'" :close-on-click-modal="true" :visible.sync="visible" :append-to-body="appendToBody">
    <el-form ref="form" :model="form" label-width="120px" :disabled="!hasLoaded">
      <el-card>
        <el-form-item label="优惠券类型" prop="couponType">
          <el-select v-model="form.couponType" placeholder="优惠券类型">
            <el-option
              v-for="item in optionOfType"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="couponImg">
          <el-image style="height:100px;float:left;border: none" :src="getImageSrc(form.couponImg)" alt="点击更换图片" fit="fill" @click="changeCouponImg">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" @click="changeCouponImg" />
            </div>
          </el-image>
        </el-form-item>
        <el-form-item label="名称" prop="couponName">
          <el-input v-model="form.couponName" />
        </el-form-item>
        <el-form-item label="使用类型" prop="useType">
          <el-select v-model="form.useType" placeholder="使用类型">
            <el-option
              v-for="item in optionOfUse"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="form.amount" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="发行数量" prop="publishCount">
          <el-input-number v-model="form.publishCount" :min="0" />
        </el-form-item>
        <el-form-item label="限领张数" prop="perLimit">
          <el-input-number v-model="form.perLimit" :min="0" />
        </el-form-item>
        <el-form-item prop="minPoint">
          <span slot="label">
            使用门槛
            <el-tooltip content="最低消费金额" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
          <el-input-number v-model="form.minPoint" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="领取所需等级" prop="memberGrowth">
          <el-select v-model="form.memberGrowth" placeholder="请选择">
            <el-option
              v-for="item in optionOfMemberGrowth"
              :key="'member_growth_' + item.id"
              :label="item.name"
              :value="item.growthPoint"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="领取有效期" prop="enableTimeRange">
          <el-date-picker style="width: 280px;"
            v-model="form.enableTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="使用有效期" prop="useTimeRange">
          <el-date-picker style="width: 280px;"
            v-model="form.useTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="优惠码" prop="code">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="发布状态" prop="publish">
          <el-select v-model="form.publish" placeholder="发布状态">
            <el-option
              v-for="item in optionOfStatus"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-card>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button v-if="hasLoaded" type="primary" icon="el-icon-check" @click="onSubmit">确 定</el-button>
      <el-button icon="el-icon-close" @click="onClose">关 闭</el-button>
    </span>

    <el-dialog title="优惠券缩略图" :modal="false" :visible.sync="openThumbnailDialog">
      <image-cropper ref="thumbnailCrop" :fixed-size="false" :upload-url="uploadThumbnailFinalUrl" @onSuccess="setThumbnail" />
    </el-dialog>
  </el-dialog>
</template>

<script>
import { couponLoad, couponSave } from '@/api/mall/coupon/manage'
import { memberLevelList } from '@/api/system/member'

export default {
  name: 'CouponFormDialog',
  data() {
    return {
      visible: false,
      appendToBody: false,
      hasLoaded: false,
      uploadThumbnailFinalUrl: `${process.env.VUE_APP_MODULE_mall_API}/api/mall/coupon/uploadThumbnailFinal`,
      form: {
        id: undefined,
        couponType: undefined,
        couponImg: undefined,
        couponName: undefined,
        useType: undefined,
        amount: 0,
        publishCount: 0,
        perLimit: 0,
        minPoint: 0,
        memberGrowth: 0,
        enableTimeRange: [],
        enableStartTime: undefined,
        enableEndTime: undefined,
        useTimeRange: [],
        startTime: undefined,
        endTime: undefined,
        code: undefined,
        publish: '1',
        remark: undefined
      },
      optionOfType: [],
      optionOfUse: [],
      optionOfMemberGrowth: [],
      optionOfStatus: [],
      openThumbnailDialog: false
    }
  },
  methods: {
    init(id) {
      this.hasLoaded = false
      this.form.id = id
      this.form.enableTimeRange = []
      this.form.useTimeRange = []
      this.visible = true
      this.$nextTick(() => {
        this.loadForm(id)
        this.getDictData()
      })
    },
    loadForm(id) {
      couponLoad({ 'id': id }).then(response => {
        this.form = this.$api.objectUpdate(this.form, response.param)
        this.form.enableTimeRange.push(this.form.enableStartTime)
        this.form.enableTimeRange.push(this.form.enableEndTime)
        this.form.useTimeRange.push(this.form.startTime)
        this.form.useTimeRange.push(this.form.endTime)
        // 判断当前用户权限
        this.hasLoaded = this.$perm.hasPermissionOr(['mall:coupon:edit'])
      }).catch(() => {
      })
    },
    getDictData() {
      const that = this
      this.$http.all([this.$dictGroup('coupon_type'), this.$dictGroup('sys_use_type'), this.$dictGroup('sys_publish_status'), memberLevelList()])
        .then(this.$http.spread(function(types, uses, status, growth) {
          that.optionOfType = types
          that.optionOfUse = uses
          that.optionOfMemberGrowth = growth
          that.optionOfStatus = status
        }))
    },
    getImageSrc(value) {
      return this.$api.getImageSrc(value)
    },
    changeCouponImg() {
      this.openThumbnailDialog = true
      this.$nextTick(() => {
        let avatarUrl
        if (this.form.thumbnail) {
          avatarUrl = this.$store.getters.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/preview/` + this.form.thumbnail
        } else {
          avatarUrl = ''
        }
        this.$refs.thumbnailCrop.init(avatarUrl)
      })
    },
    setThumbnail(avatarId) {
      this.form.couponImg = avatarId
      this.openThumbnailDialog = false
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.enableStartTime = this.form.enableTimeRange[0]
          this.form.enableEndTime = this.form.enableTimeRange[1]
          this.form.startTime = this.form.useTimeRange[0]
          this.form.endTime = this.form.useTimeRange[1]
          couponSave(this.form).then(response => {
            this.$modal.msgSuccess(response.msg)
            this.$emit('confirmForm')
            this.onClose()
          }).catch(() => {
          })
        }
      })
    },
    onClose() {
      this.$refs.form.resetFields()
      this.visible = false
    }
  }
}
</script>
